using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;


//[Serializable]
[Microsoft.SqlServer.Server.SqlUserDefinedAggregate(Format.UserDefined, MaxByteSize=256)]
public struct VectorMax : IBinarySerialize
{
    private double[] max;

    public void Init()
    {
        max = null;
    }

    public void Accumulate(SqlBinary Value)
    {
        double[] vec = Elte.SqlSpIdx.Converters.VectorConverter.ToArray(Value);

        if (max == null)
        {
            max = new double[vec.Length];
            for (int k = 0; k < max.Length; k++)
                max[k] = double.MinValue;
        }

        for (int k = 0; k < vec.Length; k++)
            max[k] = Math.Max(max[k], vec[k]);
    }

    public void Merge(VectorMax Group)
    {
        if (max == null)
        {
            max = new double[Group.max.Length];
            for (int k = 0; k < max.Length; k++)
                max[k] = double.MinValue;
        }

        for (int k = 0; k < Group.max.Length; k++)
            max[k] = Math.Max(max[k], Group.max[k]);
    }

    public SqlBinary Terminate()
    {
        return new SqlBinary(Elte.SqlSpIdx.Converters.VectorConverter.ToBinary(max));
    }

    #region IBinarySerialize Members

    public void Read(System.IO.BinaryReader r)
    {
        int length = r.ReadInt32();
        max = Elte.SqlSpIdx.Converters.VectorConverter.ToArray(r.ReadBytes(length * sizeof(double) + sizeof(int) + sizeof(int)));
    }

    public void Write(System.IO.BinaryWriter w)
    {
        w.Write(max.Length);
        w.Write(Elte.SqlSpIdx.Converters.VectorConverter.ToBinary(max));
    }

    #endregion
}
